package com.yourapp.pidinet;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.*;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.common.util.concurrent.ListenableFuture;

public class MainActivity extends AppCompatActivity {
    private static final int CAMERA_PERMISSION_CODE = 100;
    
    private PreviewView previewView;
    private ImageView overlayView;
    private DocumentEdgeDetector detector;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        previewView = findViewById(R.id.preview_view);
        overlayView = findViewById(R.id.overlay_view);
        
        try {
            detector = new DocumentEdgeDetector(this);
        } catch (Exception e) {
            e.printStackTrace();
            finish();
            return;
        }
        
        if (checkCameraPermission()) {
            startCamera();
        } else {
            requestCameraPermission();
        }
    }
    
    private boolean checkCameraPermission() {
        return ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) 
                == PackageManager.PERMISSION_GRANTED;
    }
    
    private void requestCameraPermission() {
        ActivityCompat.requestPermissions(this, 
                new String[]{Manifest.permission.CAMERA}, 
                CAMERA_PERMISSION_CODE);
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, 
                                         @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startCamera();
            } else {
                finish();
            }
        }
    }
    
    private void startCamera() {
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = 
                ProcessCameraProvider.getInstance(this);
        
        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                bindPreview(cameraProvider);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, ContextCompat.getMainExecutor(this));
    }
    
    private void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {
        Preview preview = new Preview.Builder().build();
        CameraSelector cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;
        
        ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
                .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                .build();
        
        imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this), image -> {
            // 转换为Bitmap并检测
            Bitmap bitmap = imageProxyToBitmap(image);
            DocumentEdgeDetector.DetectionResult result = detector.detectDocument(bitmap);
            
            // 在UI线程更新叠加层
            runOnUiThread(() -> updateOverlay(result));
            
            image.close();
        });
        
        preview.setSurfaceProvider(previewView.getSurfaceProvider());
        
        cameraProvider.unbindAll();
        cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis);
    }
    
    private Bitmap imageProxyToBitmap(ImageProxy image) {
        // 这里需要实现ImageProxy到Bitmap的转换
        // 简化版本，实际实现需要处理不同的图像格式
        return null; // TODO: 实现转换逻辑
    }
    
    private void updateOverlay(DocumentEdgeDetector.DetectionResult result) {
        if (result.hasDocument && result.corners != null) {
            // 创建叠加图像显示检测到的边框
            Bitmap overlayBitmap = Bitmap.createBitmap(
                    overlayView.getWidth(), overlayView.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(overlayBitmap);
            
            Paint paint = new Paint();
            paint.setColor(android.graphics.Color.GREEN);
            paint.setStrokeWidth(5f);
            paint.setStyle(Paint.Style.STROKE);
            
            // 绘制检测到的四边形
            if (result.corners.size() == 4) {
                for (int i = 0; i < 4; i++) {
                    Point start = result.corners.get(i);
                    Point end = result.corners.get((i + 1) % 4);
                    canvas.drawLine(start.x, start.y, end.x, end.y, paint);
                }
            }
            
            overlayView.setImageBitmap(overlayBitmap);
        } else {
            overlayView.setImageBitmap(null);
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (detector != null) {
            detector.close();
        }
    }
}